package com.song.cloud.payment.controller;

import com.song.cloud.common.entities.CommonResult;
import com.song.cloud.common.entities.Payment;
import com.song.cloud.payment.service.paymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author ZhangGuisong
 * @Date 2021/2/13-10:53
 */
@RestController
@Slf4j
public class paymentController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private paymentService paymentService;
    @PostMapping("/payment/save")
    public CommonResult save(@RequestBody Payment payment){
        int save = paymentService.save(payment);
        if(save>0){
            return new CommonResult(200,"数据插入并保存成功"+serverPort,save);
        }else{
            return new CommonResult(444,"数据插入失败"+serverPort,save);
        }
    }
    @GetMapping("/payment/query/{id}")
    public CommonResult query(@PathVariable("id") Long id){
        Payment query = paymentService.query(id);
        if(query!=null){
            return new CommonResult(200,"数据查询成功"+serverPort,query);
        }else{
            return new CommonResult(444,"数据查询失败"+serverPort,null);
        }
    }
    @GetMapping("/payment/discover")
    public Object getDiscoveryClient(){
        List<String> services = discoveryClient.getServices();
        for (String element: services) {
            log.info("服务名称element"+element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVICE");
        for (ServiceInstance item:instances){
            log.info("服务实例信息"+item.getServiceId()+"\t"+item.getHost()+"\t"+item.getPort()+"\t"+item.getUri());
        }
        return discoveryClient;
    }
    @GetMapping("/payment/timeOut")
    public String   timeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
